if (window.JCCU) {} else JCCU = {};
JCCU.Chatter = function()
{
	// private:
	var isRefreshing = false;

	var minimumInterval = 5000;

	var timeout = minimumInterval;

	function createLineElement(line) {
		// <div class="line"><span class="nick color1">line.nick</span>:
		// <span class="message">line.message</span></div>
		var nick = document.createElement('span');
		nick.setAttribute('class', 'nick ' + line.color);
		nick.appendChild(document.createTextNode(line.nick));

		var message = document.createElement('span');
		message.setAttribute('class', 'message');
		message.appendChild(document.createTextNode(line.message));

		var li = document.createElement('div');
		li.setAttribute('class', 'line');
		li.appendChild(nick);
		li.appendChild(document.createTextNode(': '));
		li.appendChild(message);
		return li;
	}

	function requestNewLines() {
		if (!isRefreshing)
		{
			isRefreshing = true;
			new Ajax(JCCU.Chatter.url, {
				data: { since: JCCU.Chatter.lastLinePosted },
				method: 'get',
				onComplete: function(text) {
					var chatter = Json.evaluate(text);
					if (chatter && chatter.success) {
						JCCU.Chatter.lastLinePosted = chatter.lastLinePosted;
						var firstChild = $('mod_chatter_lines').getFirst();
						for (var i = 0; i < chatter.lines.length; ++i) {
							var line = createLineElement(chatter.lines[i]);
							line.injectBefore(firstChild);
						}
					}
					else alert(text + "\n\n" + chatter.toString());
					isRefreshing = false;
				}
			}).request();
		}
	}
	
	return {
		// public:
		url: 'modules/mod_chatter/actions.php',

		lastLinePosted: 0,

		setMinimumInterval: function(value) {
			minimumInterval = value;
			timeout = value;
			setTimeout('JCCU.Chatter.update()', timeout);
		},

		submit: function(form) {
			form.task.value = 'ajax_post';
			new Ajax(JCCU.Chatter.url, {
				data: form,
				method: 'post',
				onComplete: function(text) {
					var result = Json.evaluate(text);
					if (result && result.success)
					{
						requestNewLines();
						form.message.value = '';
						form.message.focus();
						timeout = minimumInterval;
					}
					else alert(text + "\n\n" + result.toString());
				}
			}).request();
		},

		update: function() {
			requestNewLines();
			timeout *= 1.18;
			setTimeout('JCCU.Chatter.update()', timeout);
		},

		onKeyPress: function(sender, event) {
			if (13 == event.keyCode)
			{
				JCCU.Chatter.submit(sender.form);
				return false;
			}
			return true;
		}
	};
}();
